package com.zhuxiang.controller;

import com.zhuxiang.entity.User;
import com.zhuxiang.entity.Userloginlog;
import com.zhuxiang.service.UserService;
import com.zhuxiang.service.UserloginlogService;
import com.zhuxiang.util.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Controller
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private UserloginlogService userloginlogService;


    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestBody Map<String,Object> map, HttpServletRequest request, HttpSession session){
        String loginName = (String) map.get("loginName");
        String loginPwd = (String) map.get("loginPwd");
        User user = userService.selectByCellphoneOrEmailAndPwd(loginName,loginName,loginPwd);
        if (user==null){
            return "fail";
        }
        session.setAttribute("nowuser",user);
        Userloginlog userloginlog = new Userloginlog();
        userloginlog.setUserId(user.getUserId());
        userloginlog.setLoginTime(new Timestamp(new Date().getTime()));
        userloginlog.setLoginIp(request.getServerName());
        userloginlogService.addLoginlog(userloginlog);
        return "success";
    }

    @ResponseBody
    @RequestMapping("/showloginlog")
    public List<Userloginlog> selectloginlog(HttpSession session){
        User nowuser= (User) session.getAttribute("nowuser");
        return userloginlogService.selectAll(nowuser.getUserId());
    }


    @RequestMapping(value = "/register")
    @ResponseBody
    public String register(@RequestBody User user){
        String result = userService.save(user);
        return result;
    }

    @RequestMapping("/checkcellphone")
    @ResponseBody
    public String checkCellphone(String cellphone){
        User user = userService.selectByCellphone(cellphone);
        if (user == null){
            return "success";
        }
        return "fail";
    }

    @RequestMapping("/checkemail")
    @ResponseBody
    public String checkEmail(String email){
        User user = userService.selectByEmail(email);
        if (user == null){
            return "success";
        }
        return "fail";
    }
}
